import os
import sys
import django
from pathlib import Path


def setup_django_env():
    """增强版Django环境配置"""
    # 计算项目根目录（与manage.py同级）
    project_root = Path(__file__).resolve().parent.parent  # 假设脚本在myproject/scripts/目录下
    
    # 三重路径保障机制
    possible_paths = [
        project_root,                          # 层级1：项目根目录
        project_root / 'myproject',            # 层级2：Django项目目录
        project_root.parent                    # 层级3：上级目录（备用）
    ]
    
    for path in possible_paths:
        if str(path) not in sys.path:
            sys.path.insert(0, str(path))
    
    # 环境变量设置（兼容开发/生产环境）
    if not os.environ.get('DJANGO_SETTINGS_MODULE'):
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
    
    # 延迟加载Django配置
    try:
        from django.conf import settings
        if not settings.configured:
            django.setup()
    except ModuleNotFoundError as e:
        raise ImportError(f"无法导入Django模块，请检查虚拟环境: {str(e)}")

setup_django_env()

import csv
from django.db import transaction
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission


def create_groups_with_permissions():
    """创建用户组并分配权限"""
    groups_data = [
        {
            'name': '管理员',
            'permissions': [
                ('add_user', 'auth', 'user'),
                ('change_user', 'auth', 'user'),
                ('view_user', 'auth', 'user')
            ]
        },
        {
            'name': 'AOI',
            'permissions': [
                ('view_user', 'auth', 'user')
            ]
        },
        {
            'name': 'SMT',
            'permissions': [
                ('view_user', 'auth', 'user')
            ]
        },
        {
            'name': '点胶',
            'permissions': [
                ('view_user', 'auth', 'user')
            ]
        },
        {
            'name': 'PSA',
            'permissions': [
                ('view_user', 'auth', 'user')
            ]
        },
    ]

    with transaction.atomic():
        for group_info in groups_data:
            group, created = Group.objects.get_or_create(name=group_info['name'])
            if created:
                print(f'✅ 成功创建用户组: {group_info["name"]}')
                # 添加权限
                for codename, app_label, model in group_info['permissions']:
                    try:
                        perm = Permission.objects.get(
                            codename=codename,
                            content_type__app_label=app_label,
                            content_type__model=model
                        )
                        group.permissions.add(perm)
                    except Permission.DoesNotExist:
                        print(f'⚠️ 权限不存在: {codename}')
            else:
                print(f'⏩ 用户组已存在: {group_info["name"]}')

def create_superusers():
    """创建管理员账户"""
    User = get_user_model()
    admin_data = {
        'username': 'admin', 
        'email': 'admin@example.com',
        'password': 'SecurePassword123',
        'is_staff': True,
        'is_superuser': True
    }

    try:
        user = User.objects.create_user(**admin_data)
        admin_group = Group.objects.get(name='管理员')
        user.groups.add(admin_group)
        print(f'✅ 成功创建管理员: {admin_data["username"]}')
    except Exception as e:
        print(f'❌ 创建管理员失败: {str(e)}')

def bulk_create_users():
    """批量创建普通用户账户"""
    User = get_user_model()
    users_data = [
        {
            'username': 'user1',
            'email': 'user1@example.com',
            'password': 'UserPassword123',
            'is_staff': False,
            'is_superuser': False
        },
        {
            'username': 'user2',
            'email': 'user2@example.com',
            'password': 'UserPassword456',
            'is_staff': False,
        }
    ]
    try:
        users = User.objects.bulk_create([User(**data) for data in users_data])
        for user in users:
            user.set_password(user.password)
            user.save()
            print(f'✅ 成功创建普通用户: {user.username}')
    except Exception as e:
        print(f'❌ 创建普通用户失败: {str(e)}')


def import_users_from_csv(csv_path='user_list.csv'):
    """
    从CSV文件批量导入用户数据
    格式示例：
    username,email,password,is_staff,groups
    user1,user1@test.com,Password123!,False,普通用户
    admin,admin@test.com,Admin@1234,True,管理员
    """
    User = get_user_model()
    csv_file = Path(__file__).parent / csv_path
    
    if not csv_file.exists():
        raise FileNotFoundError(f"CSV文件不存在: {csv_file}")

    success_count = 0
    error_records = []

    with open(csv_file, 'r', encoding='utf-8-sig') as f:  # 处理BOM头
        reader = csv.DictReader(f)
        with transaction.atomic():  # 原子事务
            for row_num, row in enumerate(reader, start=1):
                try:
                    # 数据清洗
                    groups = [g.strip() for g in row.get('group', '').split(',') if g.strip()]  #group
                    
                    # 创建用户 (自动处理密码哈希)
                    user, created = User.objects.get_or_create(
                        username=row['username'],
                        defaults={
                            'email': row['email'],
                            'password': row['password'],  # create_user会自动哈希
                            'is_staff': row.get('is_staff', 'False').lower() == 'true',
                            'is_active': True
                        }
                    )
                    
                    # 更新已存在用户
                    if not created:
                        user.email = row['email']
                        user.is_staff = row.get('is_staff', 'False').lower() == 'true'
                        if row['password']:  # 允许密码更新
                            user.set_password(row['password'])
                        user.save()

                    # 处理用户组关联
                    if groups:
                        for group_name in groups:
                            group, _ = Group.objects.get_or_create(name=group_name)  # 创建或获取name=group_name的用户组，返回用（户组对象，isNewCreated)
                            user.groups.add(group) # 添加用户到用户组
                    
                    success_count += 1
                except Exception as e:
                    error_records.append((row_num, str(e)))
                    continue

    # 输出统计报告
    print(f"\n📊 导入完成: {success_count} 条成功")
    if error_records:
        print("❌ 失败记录:")
        for row_num, error in error_records:
            print(f"  第 {row_num} 行: {error}")

# 在main函数中调用
if __name__ == '__main__':
    try:
        setup_django_env()  # 复用之前的Django环境配置
        create_groups_with_permissions()
        import_users_from_csv()
    except Exception as e:
        print(f"❌ 导入失败: {str(e)}")

        print(f'❌ 发生未预期错误: {str(e)}')